package com.mav01.mrpbackend.service.impl;

import com.mav01.mrpbackend.mapper.DebtMapper;
import com.mav01.mrpbackend.pojo.Debt;
import com.mav01.mrpbackend.service.DebtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DebtServiceImpl implements DebtService {

    @Autowired
    private DebtMapper debtMapper;

    /**
     * 根据变量名查询行数据
     * @param variableName
     * @return
     */
    @Override
    public Debt selectByVariable(String variableName) {
        return debtMapper.selectByVariable(variableName);
    }

    /**
     * 查询全部数据
     * @return
     */
    @Override
    public List<Debt> selectAll() {
        return debtMapper.selectAll();
    }

    /**
     * 根据变量名修改一条数据
     * @param debt
     * @return
     */
    @Override
    public int update(Debt debt) {
        return debtMapper.update(debt);
    }

    /**
     * 插入一条数据
     * @param debt
     * @return
     */
    @Override
    public int insert(Debt debt) {
        return debtMapper.insert(debt);
    }

    /**
     * 根据变量名删除一条数据
     * @param variableName
     * @return
     */
    @Override
    public int deleteByVariable(String variableName) {
        return debtMapper.deleteByVariable(variableName);
    }

    /**
     * 根据变量名计算
     */
    @Override
    public String calculate(Debt debt) {
        // 根据汇总序号找到所有需要汇总的变量
        List<Debt> debts = debtMapper.selectBySummarySequence(debt);
        if (debts.isEmpty()) {
            //"未找到汇总序号为 " + debt.getVariableName() + " 的数据"
            return "最小单位";
        }

        // 构建计算公式字符串
        StringBuilder formula = new StringBuilder();
        for (Debt d : debts) {
            if (d.getVariableName() != null && !d.getVariableName().isEmpty()) {
                if (d.getAssetDirection().equals("+")) {
                    formula.append("+");
                } else if (d.getAssetDirection().equals("-")) {
                    formula.append("-");
                }
                formula.append(d.getVariableName());
            }
        }

        return formula.toString();
    }
}
